<?php

namespace services\base;

use common\components\Service;
use common\helpers\ArrayHelper;
use common\models\base\Provinces;
use Yii;

/**
 * Class ProvincesService
 * @package services\base
 */
class ProvincesService extends Service
{
    // 直辖市+香港、澳门
    const SPECIAL_CITY = [110000, 120000, 310000, 500000, 810000, 820000];

    /**
     * 根据父级ID返回信息
     * @param int $pid
     * @param string $level
     * @return array
     */
    public function getChildList(int $pid = 0, string $level = ''): array
    {
        $model = Provinces::find()
            ->where(['pid' => $pid])
            ->orderBy('id asc')
            ->select(['id', 'title', 'pid'])
            ->andFilterWhere(['level' => $level])
            ->cache(600)
            ->asArray()
            ->all();

        return ArrayHelper::map($model, 'id', 'title');
    }

    /**
     * 返回所有城市列表
     * @return array
     */
    public function getCityList(): array
    {
        $provinceId = Provinces::find()
            ->select(['id', 'title', 'pid'])
            ->where(['pid' => 0])
            ->andWhere(['not in', 'id', self::SPECIAL_CITY])
            ->orderBy('id asc')
            ->asArray()
            ->column();

        $cityArr = Provinces::find()
            ->select(['id', 'title', 'pid'])
            ->where(['pid' => $provinceId])
            ->orWhere(['id' => self::SPECIAL_CITY])
            ->orderBy('id asc')
            ->asArray()
            ->all();

        return ArrayHelper::map($cityArr, 'id', 'title');
    }

    /**
     * 投放类型下拉筛选项
     * @return array[]
     */
    public function getCityCondition(): array
    {
        $city = [];
        $cityArr = $this->getCityList();
        foreach ($cityArr as $kca => $ca) {
            $city[] = [
                'value' => $kca,
                'label' => $ca,
            ];
        }
        return $city;
    }
}
